package com.cpfmat.controller;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cpfmat.common.CommonStringUtils;
import com.cpfmat.common.Contains;
import com.cpfmat.entity.Attachment;
import com.cpfmat.entity.ContentUser;
import com.cpfmat.entity.OtherUser;
import com.cpfmat.service.IAttachmentService;
import com.cpfmat.service.IContentUserService;
import com.cpfmat.service.IOtherUserService;
import com.cpfmat.service.IRzTabService;

@Controller
public class PersonalCenterController {

	@Autowired
	private IContentUserService contentUserService;
	@Autowired
	private IOtherUserService otherUserService;
	@Autowired
	private IAttachmentService attachmentService;
	@Autowired
	private IRzTabService rzTabService;

	@RequestMapping("/push")
	public ModelAndView platform(@RequestParam(name = "keyword", required = false) String keyword,
			@RequestParam(name = "pageNum", defaultValue = "1") int pageNum) throws Exception {
		String type = "push";
		String path = "/new/pushList";
		ModelAndView view = new ModelAndView(path);

		Page<ContentUser> page = new Page<>(pageNum, Contains.PAGE_SIZE);
		EntityWrapper<ContentUser> wrapper = new EntityWrapper<ContentUser>();
		wrapper.eq("shzt", 'y').or().eq("shzt", 'Y');
		wrapper.orderBy("czsj", false);

		contentUserService.selectPage(page, wrapper);

		view.addObject("page", page);
		view.addObject("type", type);

		return view;
	}

	@RequestMapping(path = "/push/detail/{seqId}")
	public ModelAndView detail(@PathVariable("seqId") String seqId,
			@RequestParam(required = false, name = "type") String type) {
		ModelAndView view = new ModelAndView("/new/pushListDetail");

		ContentUser content = contentUserService.selectById(seqId);

		Attachment attachment = null;
		if (content != null) {
			attachment = attachmentService.selectById(content.getColumnId());
			view.addObject("attachment", attachment);
		}
		view.addObject("article", content);
		view.addObject("type", type);

		return view;
	}

	@RequestMapping("/personalCenter")
	public ModelAndView personalCenter(HttpServletRequest request) {
		OtherUser user = CommonStringUtils.getUserFromRequest(request);
		if (user != null) {
			ModelAndView view = new ModelAndView("/userCenter/changeInfo");
			view.addObject("type", "personalCenter");
			return view;
		} else {
			ModelAndView view = new ModelAndView("redirect:/index");
			view.addObject("type", "personalCenter");
			return view;
		}
	}

	@RequestMapping("/changePwd")
	public ModelAndView changePwd(HttpServletRequest request) {
		OtherUser user = CommonStringUtils.getUserFromRequest(request);
		if (user != null) {
			ModelAndView view = new ModelAndView("/userCenter/changePwd");
			view.addObject("type", "personalCenter");
			return view;
		} else {
			ModelAndView view = new ModelAndView("redirect:/index");
			return view;
		}
	}

	@RequestMapping("/sendAtri")
	public ModelAndView sendAtri(String pageNum, HttpServletRequest request) {
		Integer page = new Integer(pageNum);
		if (page < 1) {
			page = new Integer(1);
		}
		OtherUser user = CommonStringUtils.getUserFromRequest(request);
		if (user != null) {
			Page<ContentUser> list = contentUserService.getcontentByUser(user.getSqlId(), page, 10);
			List<ContentUser> result = list.getRecords();
			if ((result == null) || (result.size() <= 0)) {
				page--;
			}
			list = contentUserService.getcontentByUser(user.getSqlId(), page, 10);
			result = list.getRecords();
			ModelAndView view = new ModelAndView("/userCenter/dataList");
			view.addObject("page", page);
			view.addObject("filedatas", result);
			view.addObject("type", "personalCenter");
			view.addObject("onlyCollection", request.getParameter("onlyCollection"));
			return view;
		} else {
			ModelAndView view = new ModelAndView("redirect:/otherLogin");
			view.addObject("onlyCollection", "true");
			return view;
		}
	}

	@RequestMapping("/changeUser")
	public ModelAndView changeUser(String userName, String email, String phonenum, String ssdw,
			HttpServletRequest request) {
		ModelAndView view = new ModelAndView("/userCenter/changeInfo");

		boolean loginError = false;

		if (StringUtils.isNotBlank(userName) && userName.trim().length() > 20) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("userNameCode", "姓名不能超过20个字符");
		}
		if (StringUtils.isNotBlank(phonenum) && !CommonStringUtils.validatePhone(phonenum)) {
			loginError = true;
			view.addObject("loginError", loginError);
			view.addObject("phonenumCode", "手机号码格式不正确");
		}
		if (StringUtils.isNotBlank(email)) {
			if (email.trim().length() > 50) {
				loginError = true;
				view.addObject("loginError", loginError);
				view.addObject("emailCode", "E-mail不能超过50个字符");
			} else if (!CommonStringUtils.validateEmail(email)) {
				loginError = true;
				view.addObject("loginError", loginError);
				view.addObject("emailCode", "E-mail格式不正确");
			}
		}
		if (StringUtils.isNotBlank(ssdw)) {
			if (email.trim().length() > 200) {
				loginError = true;
				view.addObject("loginError", loginError);
				view.addObject("ssdwCode", "所属单位不能超过200个字符");
			}
		}

		if (loginError) {
			return view;
		}

		OtherUser user = CommonStringUtils.getUserFromRequest(request);

		if (user != null) {
			if (StringUtils.isNoneBlank(userName)) {
				user.setUserName(userName);
			}
			if (StringUtils.isNoneBlank(email)) {
				user.setEmail(email);
			}
			if (StringUtils.isNoneBlank(phonenum)) {
				user.setPhonenum(phonenum);
			}
			if (StringUtils.isNoneBlank(ssdw)) {
				user.setSsdw(ssdw);
			}

			rzTabService.log(user.getSqlId(), "修改基本信息", CommonStringUtils.getIpAddress(request), null);

			request.setAttribute("otherLoginUser", user);
			otherUserService.customUpdate(user);
			view.addObject("result", "更新成功！");
			view.addObject("type", "personalCenter");
		} else {
			view.setViewName("redirect:/index");
		}
		return view;
	}

	@RequestMapping("/changePwdInfo")
	public ModelAndView changePwdInfo(String userName, String oldLoginPwd, String loginPwd, String reLoginPwd,
			HttpServletRequest request) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		ModelAndView view = new ModelAndView("/userCenter/changePwd");

		OtherUser user = CommonStringUtils.getUserFromRequest(request);

		if (user != null) {
			oldLoginPwd = CommonStringUtils.md5(oldLoginPwd);
			if (oldLoginPwd.equals(user.getLoginPwd())) {
				if (loginPwd.equals(reLoginPwd)) {

					rzTabService.log(user.getSqlId(), "修改密码", CommonStringUtils.getIpAddress(request), null);

					loginPwd = CommonStringUtils.md5(loginPwd);
					user.setLoginPwd(loginPwd);
					otherUserService.customUpdate(user);
					view.addObject("result", "密码更新成功");
					request.setAttribute("otherLoginUser", user);
				} else {
					view.addObject("loginPwdCode", "两次密码输入不一致");
				}
			} else {
				view.addObject("oldLoginPwdCode", "旧密码不正确");
			}
			view.addObject("type", "personalCenter");
		} else {
			view.setViewName("redirect:/index");
		}
		return view;
	}

	@RequestMapping("/saveConetent")
	public ModelAndView saveContent(HttpServletRequest request, String fileid, String title, String subTitle,
			String content, String attachementIds, String specialField, String submission, String tecExp, String unit,
			String contactPerson, String contactPhone) {
		OtherUser user = CommonStringUtils.getUserFromRequest(request);

		if (user == null) {
			return new ModelAndView("redirect:/index");
		}

		boolean check = true;
		ModelAndView view = new ModelAndView("/userCenter/sendAtri");

		if (StringUtils.isBlank(title)) {
			check = false;
			view.addObject("titleCode", "请输入技术成果名称");
		} else if (title.length() > 200) {
			check = false;
			view.addObject("titleCode", "技术成果名称不能超过200个字符");
		}

		/*if (StringUtils.isBlank(subTitle)) {
			check = false;
			view.addObject("subTitleCode", "请输入技术成果简介");
		} else if (subTitle.length() > 200) {
			check = false;
			view.addObject("subTitleCode", "技术成果简介不能超过200个字符");
		}*/
		
		if (StringUtils.isBlank(submission)) {
			check = false;
			view.addObject("submissionCode", "请输入报送事项");
		} else if (submission.length() > 200) {
			check = false;
			view.addObject("submissionCode", "报送事项不能超过200个字符");
		}
		
		if (StringUtils.isBlank(tecExp)) {
			check = false;
			view.addObject("tecExpCode", "请输入技术成熟度");
		} else if (tecExp.length() > 200) {
			check = false;
			view.addObject("tecExpCode", "技术成熟度不能超过200个字符");
		}
		
		if (StringUtils.isBlank(unit)) {
			check = false;
			view.addObject("unitCode", "请输入报送单位");
		} else if (unit.length() > 200) {
			check = false;
			view.addObject("unitCode", "报送单位不能超过200个字符");
		}
		
		if (StringUtils.isBlank(contactPerson)) {
			check = false;
			view.addObject("contactPersonCode", "请输入联系人");
		} else if (contactPerson.length() > 200) {
			check = false;
			view.addObject("contactPersonCode", "联系人不能超过200个字符");
		}
		
		if (StringUtils.isBlank(contactPhone)) {
			check = false;
			view.addObject("contactPhoneCode", "请输入联系电话");
		} else if (contactPhone.length() > 200) {
			check = false;
			view.addObject("contactPhoneCode", "联系电话不能超过18个字符");
		} else if (!contactPhone.matches("\\d{5,}")) {
			check = false;
			view.addObject("contactPhoneCode", "联系电话格式不正确");
		}

		if (StringUtils.isBlank(content)) {
			check = false;
			view.addObject("contentCode", "请输入材料内容");
		}

		if (specialField == null || Contains.specialFieldMap.get(specialField) == null) {
			check = false;
			view.addObject("specialFieldCode", "请选择专项领域");
		}

		if (!check) {
			ContentUser contentUser = new ContentUser();
			contentUser.setTitle(title);
			contentUser.setSubTitle(subTitle);
			contentUser.setContent(content);
			contentUser.setSpecialField(specialField);
			
			contentUser.setSubmission(submission);
			contentUser.setTecExp(tecExp);
			contentUser.setUnit(unit);
			contentUser.setContactPerson(contactPerson);
			contentUser.setContactPhone(contactPhone);

			view.addObject("content", contentUser);
			
			if (attachementIds != null) {
				List<Attachment> attachments = attachmentService.selectBatchIds(Arrays.asList(attachementIds.split("#")));
				view.addObject("attachments", attachments);
				view.addObject("type", "personalCenter");
			}
			return view;
		}

		ContentUser contentUser = contentUserService.selectById(fileid);
		if (contentUser == null) {

			contentUser = new ContentUser();
			contentUser.setSqlId(CommonStringUtils.getUUID());
			contentUser.setColumnId(attachementIds);

			contentUser.setContent(content);
			contentUser.setTitle(title);
			contentUser.setSubTitle(subTitle);
			contentUser.setShzt("W");
			contentUser.setUserId(user.getSqlId());
			contentUser.setCzsj(new Date());
			contentUser.setSpecialField(specialField);
			
			contentUser.setSubmission(submission);
			contentUser.setTecExp(tecExp);
			contentUser.setUnit(unit);
			contentUser.setContactPerson(contactPerson);
			contentUser.setContactPhone(contactPhone);

			contentUser.insert();
			// 记录日志
			rzTabService.log(user.getSqlId(), "新增报送材料", CommonStringUtils.getIpAddress(request), null);
		} else {
			contentUser.setColumnId(attachementIds);

			contentUser.setContent(content);
			contentUser.setTitle(title);
			contentUser.setSubTitle(subTitle);
			contentUser.setShzt("W");
			contentUser.setUserId(user.getSqlId());
			contentUser.setCzsj(new Date());
			contentUser.setSpecialField(specialField);
			
			contentUser.setSubmission(submission);
			contentUser.setTecExp(tecExp);
			contentUser.setUnit(unit);
			contentUser.setContactPerson(contactPerson);
			contentUser.setContactPhone(contactPhone);
			
			contentUserService.customUpdate(contentUser);
			// 记录日志
			rzTabService.log(user.getSqlId(), "修改报送材料", CommonStringUtils.getIpAddress(request), null);
		}

		Page<ContentUser> list = contentUserService.getcontentByUser(user.getSqlId(), 1, Contains.PAGE_SIZE);
		List<ContentUser> result = list.getRecords();

		view.setViewName("/userCenter/dataList");
		view.addObject("onlyCollection", request.getParameter("onlyCollection"));
		view.addObject("page", request.getParameter("pageNum"));
		view.addObject("filedatas", result);
		view.addObject("result", "保存成功");
		view.addObject("type", "personalCenter");
		return view;
	}

	@RequestMapping("/editFile")
	public ModelAndView editFile(String fileid, HttpServletRequest request) {
		ModelAndView view = new ModelAndView("/userCenter/sendAtri");

		ContentUser content = contentUserService.selectById(fileid);

		view.addObject("content", content);

		String userId = CommonStringUtils.getUserIdFromRequest(request);

		if (userId != null) {
			if (content != null && userId.equals(content.getUserId()) && content.getColumnId() != null) {
				List<Attachment> attachments = attachmentService
						.selectBatchIds(Arrays.asList(content.getColumnId().split("#")));
				view.addObject("attachments", attachments);
				view.addObject("type", "personalCenter");
			}
			view.addObject("onlyCollection", request.getParameter("onlyCollection"));
			view.addObject("pageNum", request.getParameter("pageNum"));
			return view;
		} else {
			view.setViewName("redirect:/index");
			return view;
		}
	}

	@RequestMapping("/previewContentUser")
	public ModelAndView previewContentUser(String seqId, String pageNum, HttpServletRequest request) {
		ModelAndView view = new ModelAndView("/userCenter/contentUserPreview");

		ContentUser content = contentUserService.selectById(seqId);

		view.addObject("content", content);

		String userId = CommonStringUtils.getUserIdFromRequest(request);

		if (userId != null) {
			if (content != null && userId.equals(content.getUserId()) && content.getColumnId() != null) {
				List<Attachment> attachments = attachmentService
						.selectBatchIds(Arrays.asList(content.getColumnId().split("#")));
				view.addObject("attachments", attachments);
			}
			view.addObject("pageNum", pageNum);
			view.addObject("type", "personalCenter");
			view.addObject("onlyCollection", request.getParameter("onlyCollection"));
			return view;
		} else {
			view.setViewName("redirect:/index");
			return view;
		}
	}

	@RequestMapping("/deleteFile")
	public ModelAndView deleteFile(String fileid, HttpServletRequest request) {
		ModelAndView view = new ModelAndView("/userCenter/dataList");

		String userId = CommonStringUtils.getUserIdFromRequest(request);

		ContentUser content = contentUserService.selectById(fileid);
		if (userId != null) {
			if (content != null && userId.equals(content.getUserId())) {
				rzTabService.log(userId, "删除报送材料", CommonStringUtils.getIpAddress(request), null);

				content.deleteById();

				view.addObject("result", "删除成功");
			} else {
				view.addObject("result", "删除失败");
			}

			Page<ContentUser> list = contentUserService.getcontentByUser(userId, 1, 10);
			List<ContentUser> result = list.getRecords();
			view.addObject("filedatas", result);
			view.addObject("type", "personalCenter");
			view.addObject("pageNum", request.getParameter("pageNum"));
			view.addObject("onlyCollection", request.getParameter("onlyCollection"));
		} else {
			view.setViewName("redirect:/index");
		}
		return view;

	}
}
